{% from "macros/forms.html" import form_input %}
{% set form_error = form_error | default({}) %}
{% set placeholder = 'new_template' if template.id == '0' else template.id %}


<!-- Template Validation Status Display -->
{% if validation_status and template.id != '0' %}<div class="w-3/4 mb-5">{{ validation_status | render_validation_status }}</div>{% endif %}

<form id="{{ model_name }}-form"
      {{ form_action }}
      hx-swap="innerHTML"
      hx-target="#form-container"
      hx-target-error="#notification-bar"
      data-template-editor-sync="syncEditorContent"
      onsubmit="return syncEditorContent()">
  <label class="tooltip floating-label w-3/4 mb-5" {% if template.id != '0' %}data-tip="Filename can't be changed, create a new template"{% endif %}>
    <span class="label">Filename</span>
    <input id="id"
           type="text"
           placeholder="Enter filename..."
           name="id"
           value="{{ '' if template.id == '0' else template.id }}"
           required
           pattern="^[\w\.\-]+$"
           class="input w-full validator {% if template.id != '0' %}bg-base-200 text-base-content opacity-60 pointer-events-none select-none{% endif %}"
           {% if template.id != '0' %}readonly{% endif %} />
    <p class="validator-hint">Must be a valid filename</p>
  </label>

  <textarea name="content" id="editor-content" class="w-3/4 min-h-[60vh]">{{ template.content if template.content else '\n'*42 }}</textarea>

  <div class="bg-base-100 editor w-3/4 min-h-[60vh]" id="editor"></div>

  <input type="submit" class="btn btn-primary w-3/4 mt-5" value="{{ submit_text }}" />
</form>

<script type="text/javascript">
  const formId = '{{ model_name }}-form';
  let templateEditor = null;

  function initTemplateEditor() {
    if (!window.TemplateEditor) {
      console.warn("TemplateEditor bundle not loaded; unable to initialise CodeMirror.");
      return;
    }

    if (templateEditor && typeof templateEditor.destroy === 'function') {
      templateEditor.destroy();
    }

    const textarea = document.getElementById('editor-content');
    const host = document.getElementById('editor');
    if (!textarea || !host) {
      return;
    }

    templateEditor = window.TemplateEditor.mount({ textarea, parent: host });
  }

  window.syncEditorContent = function syncEditorContent() {
    if (templateEditor && typeof templateEditor.sync === 'function') {
      templateEditor.sync();
    }
    return true;
  };

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initTemplateEditor, { once: true });
  } else {
    initTemplateEditor();
  }

  if (!window.__templateEditorAfterSwapHandler) {
    window.__templateEditorAfterSwapHandler = (event) => {
      if (event.target && event.target.id === formId) {
        initTemplateEditor();
      }
    };
    document.addEventListener('htmx:afterSwap', window.__templateEditorAfterSwapHandler);
  }
</script>
